package service

import (
	"anban/models"
	"github.com/astaxie/beego/orm"
	"net/url"
)

// 获取权限分类信息
func GetAuthorityCategoryInfo(p map[string]interface{}) *models.AuthorityCategory {
	o := orm.NewOrm()
	authorityCategory := &models.AuthorityCategory{}
	qs := o.QueryTable("AuthorityCategory")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(authorityCategory)
	return authorityCategory
}

// 添加权限分类信息
func AddAuthorityCategory(input url.Values) (int64, error) {
	o := orm.NewOrm()
	authorityCategory := &models.AuthorityCategory{}
	if _, ok := input["name"]; ok {
		authorityCategory.Name = input["name"][0]
	}
	return o.Insert(authorityCategory)
}

// 修改权限分类信息
func EditAuthorityCategory(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("AuthorityCategory").Filter("id", input["id"][0]).Update(p)
}

// 获取权限分类列表
func GetAuthorityCategoryList(p map[string]interface{}) (int64, []*models.AuthorityCategory) {
	var authorityCategoryList []*models.AuthorityCategory
	o := orm.NewOrm()
	qs := o.QueryTable("AuthorityCategory")
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&authorityCategoryList)
	return totalCount, authorityCategoryList
}

func GetAllAuthority(p map[string]interface{}) []*models.AuthorityCategory {
	param := map[string]interface{}{}
	_, authorityCategoryList := GetAuthorityCategoryList(param)
	for _, authorityCategory := range authorityCategoryList {
		param = map[string]interface{}{}
		param["authorityCategoryId"] = authorityCategory.Id
		_, authorityList := GetAuthorityList(param)
		authorityCategory.Children = authorityList
		if _, ok := p["userAdminRoleId"]; ok {
			for _, authority := range authorityList {
				param = map[string]interface{}{}
				param["userAdminRoleId"] = p["userAdminRoleId"]
				param["authorityId"] = authority.Id
				roleAuthority := GetUserAdminRoleAuthorityInfo(param)
				if roleAuthority.Id > 0 {
					authority.IsChecked = true
				} else {
					authority.IsChecked = false
				}
			}
		}
	}
	return authorityCategoryList
}